package com.ztom.offer.v2;

import java.util.List;

/**
 * 链表中倒数第 K 个节点
 * <p>
 * https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
 *
 * @author ZhangTao
 */
public class Code21GetKthFromEnd {

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null) {
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;

        // 快指针先走 k 步
        while (fast != null && k > 0) {
            fast = fast.next;
            k--;
        }
        // 然后同步走
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}
